import { Commit} from "vuex";

export interface ICrossPageState {
  hubs: IHub;
}

export interface IHub {
  [moduleName: string]: IHubEvent[];
}

export interface IHubEvent {
  method: string;
  params: any;
}

export default {
  namespaced: true,
  state(): ICrossPageState {
    return {
      hubs: {},
    }
  },

  mutations: {
    createHub(state: ICrossPageState, moduleName: string) {
      state.hubs[moduleName] = []
    },

    clearModule(state: ICrossPageState, moduleName: string) {
      state.hubs[moduleName] = []
    },

    storeEvent(state: ICrossPageState, payload: {moduleName: string, method: string; params: any}) {
      state.hubs[payload.moduleName].push({
        method: payload.method,
        params: payload.params
      })
    }
  },

  actions: {
    registerEvents({state, commit}: {state: ICrossPageState, commit: Commit}, moduleName: string) {
      if (!state.hubs[moduleName]) {
        commit("createHub", moduleName)
      }
    },
  },
}
